<template>
  <div class="document-management">
    <!-- 查询表单 -->
    <el-form class="demo-form-inline" ref="formRef" :model="queryForm" label-width="100px" size="small" inline>
      <el-form-item label="文件名" prop="name">
        <el-input v-model="queryForm.name" placeholder="请输入文件名" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
          <el-option label="待审核" value="待审核"></el-option>
          <el-option label="已通过" value="已通过"></el-option>
          <el-option label="未通过" value="未通过"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fetchDocuments">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-refresh" @click="resetData">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="el-row">
      <el-button type="primary" icon="el-icon-upload" plain size="small" @click="showUploadDialog">上传文件</el-button>
      <el-button type="danger" icon="el-icon-delete" plain size="small" :disabled="selectedRows.length === 0" @click="batchDelete">批量删除</el-button>
    </div>

    <!-- 文件列表表格 -->
    <el-table
      :data="filteredFileList"
      height="100%"
      style="width: 100%;"
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="name" label="文件名"></el-table-column>
      <el-table-column prop="type" label="类型"></el-table-column>
      <el-table-column prop="uploadTime" label="上传时间"></el-table-column>
      <el-table-column prop="creator" label="创建人"></el-table-column>
      <el-table-column prop="status" label="审核状态">
        <template slot-scope="scope">
          <span :class="{'pending': scope.row.status === '待审核', 'approved': scope.row.status === '已通过', 'rejected': scope.row.status === '未通过'}">{{ scope.row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="right">
        <template slot-scope="scope">
          <el-button type="text" @click="auditFile(scope.row)" v-if="scope.row.status === '待审核'">审核</el-button> <!-- 只有“待审核”状态的文件显示审核按钮 -->
          <el-button type="text" @click="previewFile(scope.row)">预览</el-button>
          <el-button type="text" @click="editFile(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      background
      style="text-align: right"
    ></el-pagination>

    <!-- 上传文件对话框 -->
    <UploadDocumentDialog :visible.sync="uploadDialogVisible" @on-success="handleUploadSuccess"/>

    <!-- 预览、编辑、审核 -->
    <DocumentPreview :visible.sync="previewDialogVisible" :file="selectedFile"/>
    <DocumentEditor :visible.sync="editorDialogVisible" :file="selectedFile"/>
    <DocumentAudit :visible.sync="auditDialogVisible" :file="selectedFile" @submit="handleAuditSubmit"/>
  </div>
</template>

<script>
import UploadDocumentDialog from './components/UploadDocumentDialog.vue';
import DocumentPreview from './components/DocumentPreview.vue';
import DocumentEditor from './components/DocumentEditor.vue';
import DocumentAudit from './components/DocumentAudit.vue';

export default {
  name: "DocumentManagement",
  components: { UploadDocumentDialog, DocumentPreview, DocumentEditor, DocumentAudit },
  data() {
    return {
      queryForm: {
        name: "",
        status: ''
      },
      totalFileList: [],
      fileList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      selectedRows: [],
      loading: false,
      uploadDialogVisible: false,
      previewDialogVisible: false,
      editorDialogVisible: false,
      auditDialogVisible: false,
      selectedFile: {}
    };
  },
  computed: {
    filteredFileList() {
      return this.fileList.filter(file => {
        const matchesName = !this.queryForm.name || file.name.includes(this.queryForm.name);
        const matchesStatus = !this.queryForm.status || file.status === this.queryForm.status;
        return matchesName && matchesStatus;
      });
    }
  },
  methods: {
    showUploadDialog() {
      this.uploadDialogVisible = true;
    },
    handleUploadSuccess(newFiles) {
      newFiles.forEach((file, index) => {
        file.id = Math.max(...this.totalFileList.map(f => f.id), 0) + index + 1; // 确保唯一ID
        this.totalFileList.push(file);
      });
      this.fetchDocuments(); // 重新获取并计算过滤后的文件列表
    },
    fetchDocuments() {
      this.loading = true;
      setTimeout(() => {
        const {name, status} = this.queryForm;
        const filteredData = this.totalFileList.filter(item => {
          return (
            (!name || item.name.includes(name)) &&
            (!status || item.status === status)
          );
        });
        this.total = filteredData.length;
        this.fileList = filteredData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
        this.loading = false;
      }, 1000);
    },
    resetData() {
      this.$refs.formRef.resetFields();
      this.fetchDocuments();
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该文件信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.totalFileList = this.totalFileList.filter(file => file.id !== row.id);
        this.fetchDocuments(); // 重新获取并计算过滤后的文件列表
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    batchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的文件信息!'
        });
        return;
      }

      this.$confirm('此操作将永久删除选中的文件信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const idsToDelete = this.selectedRows.map(row => row.id);
        this.totalFileList = this.totalFileList.filter(file => !idsToDelete.includes(file.id));
        this.fetchDocuments(); // 重新获取并计算过滤后的文件列表
        this.selectedRows = [];
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    previewFile(file) {
      this.selectedFile = file;
      this.previewDialogVisible = true;
    },
    editFile(file) {
      this.selectedFile = file;
      this.editorDialogVisible = true;
    },
    auditFile(file) {
      this.selectedFile = file;
      this.auditDialogVisible = true;
    },
    handleAuditSubmit(updatedFile) {
      const index = this.totalFileList.findIndex(file => file.id === updatedFile.id);
      if (index > -1) {
        this.$set(this.totalFileList, index, { ...this.totalFileList[index], ...updatedFile });
        this.fetchDocuments(); // 重新获取并计算过滤后的文件列表
      }
      this.auditDialogVisible = false;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchDocuments();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchDocuments();
    }
  },
  mounted() {
    // 初始化数据
    this.totalFileList = [
      { id: 1, name: '报告1.docx', type: 'Word', uploadTime: '2023-01-01', creator: '张三', status: '待审核' },
      { id: 2, name: '报告2.xlsx', type: 'Excel', uploadTime: '2023-01-02', creator: '李四', status: '已通过' },
      { id: 3, name: '报告3.docx', type: 'Word', uploadTime: '2023-01-03', creator: '王五', status: '未通过' }
    ];
    this.fetchDocuments();
  }
};
</script>

<style scoped lang="scss">
.document-management {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;

  .el-row {
    margin-bottom: 20px;
  }

  .el-table {
    flex: 1;
    margin-bottom: 20px;
  }

  .pending {
    color: orange;
  }

  .approved {
    color: green;
  }

  .rejected {
    color: red;
  }
}
</style>
